<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>录屏</title>
	<style>
		video {
			border: 1px solid black;
			max-width: 100%;
		}
	</style>
</head>
<body>
<video id="recorded" width="640" height="480" controls></video>
<div id="duration"></div>
<button id="startButton">开始录制</button>
<button id="stopButton" disabled>停止录制</button>
<button id="saveButton" disabled>保存录制文件</button>
<img id="imagePreview" style="display: none;" />
<select id="videoSelect"></select>
<a id="downloadButton" disabled>下载录制文件</a>

<script>
	const video = document.getElementById('recorded');
	const durationDiv = document.getElementById('duration');
	const startButton = document.getElementById('startButton');
	const stopButton = document.getElementById('stopButton');
	const saveButton = document.getElementById('saveButton');
	const imagePreview = document.getElementById('imagePreview');
	const videoSelect = document.getElementById('videoSelect');
	const downloadButton = document.getElementById('downloadButton');
	let mediaStream;
	let mediaRecorder;
	let chunks = [];
	let videos = [];
	let startTime = 0;
	let timer; // 计时器

	function startRecording() {
		navigator.mediaDevices.getDisplayMedia({video: true, audio: true})
				.then(function(stream) {
					mediaStream = stream;
					video.srcObject = stream;
					mediaRecorder = new MediaRecorder(stream);
					chunks = [];
					startTime = new Date().getTime();

					startButton.disabled = true;
					stopButton.disabled = false;
					saveButton.disabled = true;
					downloadButton.disabled = true;

					mediaRecorder.ondataavailable = function(e) {
						chunks.push(e.data);
					};

					mediaRecorder.onstop = function(e) {
						const blob = new Blob(chunks, {type: 'video/mp4'});
						chunks = [];

						const videoURL = URL.createObjectURL(blob);
						const duration = (new Date().getTime() - startTime) / 1000; // 计算录制时长
						const videoItem = {
							url: videoURL,
							name: 'recorded-video-' + new Date().toLocaleString().replaceAll('/', '-') + ' (' + formatDuration(duration) + '-' + formatSize(blob.size) + ')'
						};
						videos.unshift(videoItem); // 添加到最近录制的视频列表开头
						if (videos.length > 5) {
							videos.pop(); // 删除最老的视频
						}

						updateVideoSelect();
						selectLatestVideo();

						startButton.disabled = false;
						stopButton.disabled = true;
						saveButton.disabled = false;
						downloadButton.disabled = false;
						startTime = 0; // 计时器归零
					};

					mediaRecorder.start();
					updateRecordingDuration();
				})
				.catch(function(error) {
					console.error('Failed to capture video:', error);
				});
	}

	function stopRecording() {
		if (!mediaRecorder) return;

		mediaRecorder.stop();
		clearInterval(timer); // 停止计时器
		video.srcObject = null;
		stopSharing();


		startButton.disabled = false;
		stopButton.disabled = true;
		saveButton.disabled = false;
	}

	function stopSharing() {
		if (mediaStream) {
			mediaStream.getTracks().forEach(track => track.stop());
			mediaStream = null;
		}
	}

	function saveRecording() {
		if (videoSelect.selectedIndex === -1) return;

		const selectedVideo = videos[videoSelect.selectedIndex];
		const link = document.createElement('a');
		link.href = selectedVideo.url;
		link.download = selectedVideo.name + '.mp4';
		link.click();
	}

	function updateVideoSelect() {
		videoSelect.innerHTML = '';
		for (let i = 0; i < videos.length; i++) {
			const option = document.createElement('option');
			option.value = i;
			option.innerHTML = videos[i].name;
			videoSelect.appendChild(option);
		}
	}

	function selectLatestVideo() {
		videoSelect.selectedIndex = 0;
		video.src = videos[0].url;
	}

	function updateRecordingDuration() {
		clearInterval(timer); // 清除之前的计时器
		timer = setInterval(function() {
			const currentTime = new Date().getTime();
			const duration = (currentTime - startTime) / 1000; // 计算录制时长
			durationDiv.textContent = '录制时长：' + formatDuration(duration);
		}, 1000);
	}

	function formatDuration(duration) {
		const hours = Math.floor(duration / 3600);
		const minutes = Math.floor((duration % 3600) / 60);
		const seconds = Math.floor(duration % 60);
		return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
	}

	function formatSize(size) {
		if (size < 1024) {
			return size + 'B';
		} else if (size < 1024 * 1024) {
			return (size / 1024).toFixed(2) + 'KB';
		} else if (size < 1024 * 1024 * 1024) {
			return (size / (1024 * 1024)).toFixed(2) + 'MB';
		} else {
			return (size / (1024 * 1024 * 1024)).toFixed(2) + 'GB';
		}
	}

	startButton.addEventListener('click', startRecording);
	stopButton.addEventListener('click', stopRecording);
	saveButton.addEventListener('click', saveRecording);
	selectLatestVideo();

</script>
</body>
</html>